﻿using System;
using System.Collections.Generic;
using Core;
using Core.Event;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.PlayerLoop;
using Util;

namespace Game {
    public class Player {
        public GameObject PlayerObj { get; private set; }

        public PlayerComponent Component { get; private set; }
        public PlayerController Controller { get; private set; }

        public PlayerEquipModule EquipModule { get; private set; }
        
        public PlayerBagModule BagModule { get; private set; }
        
        public PlayerTradeModule TradeModule { get; private set; }

        public PlayerDataSO PlayerData { get; private set; }

        private readonly HashSet<PlayerModule> mPlayerModules;

        public Player(string name) {
            mPlayerModules = new HashSet<PlayerModule>();
            PlayerObj = AssetLoader.InstantiateGameObject(PrefabNames.PLAYER);
            PlayerObj.name = name;
            Component = PlayerObj.GetComponent<PlayerComponent>();
            Component.OnPlayerStart += onStart;
            Component.OnPlayerDestroy += onDestroy;
        }

        private void onStart() {
            //数据加载
            PlayerData = ResourceMgr.Ins.LoadData<PlayerDataSO>("PlayerData");
            
            //模块加载
            initModules();
            
            GameEventMgr.Ins.PushEvent(GameEventID.PlayerInit);
        }

        private void initModules() {
            //移动模块
            Controller = new PlayerController(this);
            //背包模块
            BagModule = new PlayerBagModule(this);
            //装备模块
            EquipModule = new PlayerEquipModule(this);
            //交易模块
            TradeModule = new PlayerTradeModule(this);
            
            foreach (var module in mPlayerModules) {
                module.Init();
            }
        }

        private void onDestroy() {
            //卸载模块
            foreach (var module in mPlayerModules) {
                module.Release();
            }
        }

        /// <summary>
        /// 注册模块接口
        /// </summary>
        public void RegisterModule(PlayerModule module) {
            mPlayerModules.Add(module);
        }

        /// <summary>
        /// 注销模块接口
        /// </summary>
        public void UnRegisterModule(PlayerModule module) {
            mPlayerModules.Remove(module);
        }
    }
}